<template>
  <div class="account-settings-info-view">
    <a-row :gutter="16">
      <a-col :md="24" :lg="10">
        <a-form-model ref="form" :model="model" :rules="validatorRules" v-bind="layout">
          <a-form-model-item label="真实姓名" prop="realname">
            <a-input v-model="model.realname" placeholder="输入真实姓名" disabled allowClear/>
          </a-form-model-item>
          <a-form-model-item label="性别">
            <a-select v-model="model.sex" default-value="0" optionFilterProp="label" style="width: 120px" @change="changeSex">
              <a-select-option :value="0">
                请选择...
              </a-select-option>
              <a-select-option :value="1" label="男">
                男
              </a-select-option>
              <a-select-option :value="2" label="女">
                女
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="邮箱">
            <a-input v-model="model.email" placeholder="输入邮箱" allowClear/>
          </a-form-model-item>
          <a-form-model-item label="联系电话" prop="phone">
            <a-input v-model="model.phone" placeholder="输入联系电话" allowClear />
          </a-form-model-item>
<!--          <a-form-model-item label="部门" >-->
<!--            <a-input disabled />-->
<!--          </a-form-model-item>-->
          <a-form-model-item>
            <a-button type="primary" :loading="loadData" @click="editOk">保存</a-button>
          </a-form-model-item>
        </a-form-model>
      </a-col>
      <a-col :md="24" :lg="14" :style="{ minHeight: '180px' }">
        <div style="width: 300px;margin: 0 auto">
          <a-upload
            :accept="accept"
            :action="uploadAction"
            :headers="headers"
            :before-upload="beforeUpload"
            :transformFile="transformFile"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            @change="handleChange"
          >
            <a-spin :spinning=loading >
              <img v-if="model.avatar" :src="model.avatar" class="img" alt="avatar" />
              <div v-else class="img">
                <a-icon :type="loading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">
                  Upload
                </div>
              </div>
            </a-spin>
          </a-upload>
        </div>
        <!--        <div class="ant-upload-preview" @click="$refs.modal.edit(1)" >-->
        <!--          <a-icon type="cloud-upload-o" class="upload-icon"/>-->
        <!--          <div class="mask">-->
        <!--            <a-icon type="plus" />-->
        <!--          </div>-->
        <!--          <img :src="model.avatar"/>-->
        <!--        </div>-->
      </a-col>
    </a-row>
<!--    <avatar-modal ref="modal"></avatar-modal>-->
  </div>
</template>

<script>
  import { mapGetters } from "vuex";
  import * as imageConversion from 'image-conversion'
  import Vue from 'vue'
  import { ACCESS_TOKEN, USER_INFO } from "@/store/mutation-types"
  import { postAction } from "@api/manage";
  import { duplicateCheck } from '@/api/api'
  export default {
    data () {
      return {
        // cropper
        headers: {},
        loading: false,
        loadData: false,
        model: {},
        validatorRules: {
          realname: [{ required: true, message: '真实姓名不能为空', trigger: 'change' }],
          phone: [
            { required: true, message: '联系电话不能为空', trigger: 'change' },
            { validator: this.validatePhone }
          ],
        },
        layout: {
          labelCol: { span: 5 },
          wrapperCol: { span: 18 },
        },
        accept: '.png, .jpg, .jpeg',
        url: {
          edit: '/sys/user/editSysUser'
        },
        uploadAction: window._CONFIG['domianURL'] + "/sys/oss/file/upload",
      }
    },
    mounted() {
      this.model = {...this.userInfo()};
    },
    created(){
      const token = Vue.ls.get(ACCESS_TOKEN);
      this.headers = { "X-Access-Token": token };
    },
    methods: {
      ...mapGetters(["userInfo"]),
      changeSex(value) {
        if(value !== 0) {
          this.model.sex = value;
        }
      },
      editOk() {
        if(this.model.sex == 0) {
          delete this.model.sex;
        }

        let params = {
          id: this.model.id,
          realname: this.model.realname,
          sex: this.model.sex,
          phone: this.model.phone,
          email: this.model.email,
          avatar: this.model.avatar
        }
        this.loadData = true;
        postAction(this.url.edit, params).then((res) => {
          if (res.success) {
            Vue.ls.set(USER_INFO, this.model, 7 * 24 * 60 * 60 * 1000)
            this.$store.commit("SET_AVATAR", this.model.avatar);
            this.$message.success(res.message)
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.loadData = false;
        })
      },
      handleChange(info) {
        if (info.file.status === 'uploading') {
          this.loading = true;
          return;
        }
        if (info.file.status === 'done') {
          if (info.file.response.success) {
            this.loading = false;
            this.model.avatar = info.file.response.result;
          }
        } else if (info.file.status === 'error') {
          this.loading = false;
          this.$message.error(`${info.file.name} 上传失败.`);
        }
      },
      transformFile(file) {
        return new Promise((resolve) => {
          if (file.size > 5 * 1024 * 1024) {
            imageConversion.compress(file,0.8).then(res => {
              res = new File([res], file.name, {type: res.type, lastModified: Date.now()})
              resolve(res)
            })
          } else {
            resolve(file);
          }
        })
      },
      beforeUpload(file) {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
          this.$message.error('图片格式不正确!');
        }
        const isLt2M = file.size / 1024 / 1024 < 30;
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过30MB!');
        }
        return isJpgOrPng && isLt2M;
      },
      validatePhone(rule, value, callback){
        if(!value){
          callback()
        }else{
          if(new RegExp(/^1[3|4|5|6|7|8|9][0-9]\d{8}$/).test(value)){
            let params = {
              tableName: 'sys_user',
              fieldName: 'phone',
              fieldVal: value,
              dataId: this.model.id
            };
            duplicateCheck(params).then((res) => {
              if (res.success) {
                callback()
              } else {
                callback("手机号已存在!")
              }
            })
          } else {
            callback("请输入正确格式的手机号码!");
          }
        }
      },
    },
  }
</script>

<style lang="less" scoped>
.img {
  width: 150px;
  height: 150px;
  border-radius: 150px;
  object-fit: cover;
}
</style>